<template>
	<view class="address-edit-container">
		<!-- 导航栏 -->
		<view class="nav-bar">
			<view class="nav-left" @click="goBack">
				<text class="iconfont icon-arrow-left"></text>
			</view>
			<view class="nav-title">{{ isEdit ? '编辑地址' : '新增地址' }}</view>
			<view class="nav-right"></view>
		</view>
		
		<!-- 表单内容 -->
		<scroll-view scroll-y class="form-container">
			<view class="form-section">
				<!-- 联系人信息 -->
				<view class="form-item">
					<view class="item-label">收货人</view>
					<input 
						v-model="form.name" 
						class="item-input" 
						placeholder="请输入收货人姓名"
						maxlength="20"
					/>
				</view>
				
				<view class="form-item">
					<view class="item-label">手机号</view>
					<input 
						v-model="form.phone" 
						class="item-input" 
						placeholder="请输入手机号"
						type="number"
						maxlength="11"
					/>
				</view>
			</view>
			
			<view class="form-section">
				<!-- 地区选择 -->
				<view class="form-item" @click="showRegionPicker">
					<view class="item-label">所在地区</view>
					<view class="item-content">
						<text v-if="regionText" class="region-text">{{ regionText }}</text>
						<text v-else class="placeholder-text">请选择省市区</text>
						<text class="iconfont icon-arrow-right"></text>
					</view>
				</view>
				
				<!-- 详细地址 -->
				<view class="form-item">
					<view class="item-label">详细地址</view>
					<textarea 
						v-model="form.detail" 
						class="item-textarea" 
						placeholder="请输入详细地址，如街道、楼牌号等"
						maxlength="200"
						auto-height
					/>
				</view>
			</view>
			
			<view class="form-section">
				<!-- 设为默认地址 -->
				<view class="form-item switch-item" @click="toggleDefault">
					<view class="item-label">设为默认地址</view>
					<switch 
						:checked="form.isDefault" 
						@change="onDefaultChange"
						color="#007aff"
					/>
				</view>
			</view>
			
			<!-- 定位获取地址 -->
			<view class="location-section">
				<view class="location-btn" @click="getCurrentLocation">
					<text class="iconfont icon-location"></text>
					<text class="location-text">使用当前位置</text>
				</view>
			</view>
		</scroll-view>
		
		<!-- 底部保存按钮 -->
		<view class="save-btn-container">
			<view 
				class="save-btn" 
				:class="{ disabled: !canSave }"
				@click="saveAddress"
			>
				{{ loading ? '保存中...' : '保存' }}
			</view>
		</view>
		
		<!-- 地区选择器 -->
		<picker-view 
			v-if="showPicker" 
			class="region-picker"
			:value="pickerValue"
			@change="onPickerChange"
		>
			<picker-view-column>
				<view v-for="(item, index) in provinces" :key="index" class="picker-item">
					{{ item.name }}
				</view>
			</picker-view-column>
			<picker-view-column>
				<view v-for="(item, index) in cities" :key="index" class="picker-item">
					{{ item.name }}
				</view>
			</picker-view-column>
			<picker-view-column>
				<view v-for="(item, index) in districts" :key="index" class="picker-item">
					{{ item.name }}
				</view>
			</picker-view-column>
		</picker-view>
		
		<!-- 地区选择器遮罩 -->
		<view v-if="showPicker" class="picker-mask" @click="hidePicker">
			<view class="picker-header" @click.stop>
				<view class="picker-cancel" @click="hidePicker">取消</view>
				<view class="picker-title">选择地区</view>
				<view class="picker-confirm" @click="confirmRegion">确定</view>
			</view>
		</view>
	</view>
</template>

<script>
import api from '@/api'

export default {
	data() {
		return {
			isEdit: false,
			addressId: null,
			loading: false,
			form: {
				name: '',
				phone: '',
				province: '',
				city: '',
				district: '',
				detail: '',
				isDefault: false
			},
			// 地区选择器
			showPicker: false,
			pickerValue: [0, 0, 0],
			provinces: [],
			cities: [],
			districts: []
		}
	},
	
	computed: {
		// 地区文本
		regionText() {
			if (this.form.province && this.form.city && this.form.district) {
				return `${this.form.province} ${this.form.city} ${this.form.district}`
			}
			return ''
		},
		
		// 是否可以保存
		canSave() {
			return this.form.name.trim() && 
				   this.form.phone.trim() && 
				   this.form.province && 
				   this.form.city && 
				   this.form.district && 
				   this.form.detail.trim() &&
				   !this.loading
		}
	},
	
	onLoad(options) {
		if (options.id) {
			this.isEdit = true
			this.addressId = options.id
			this.loadAddressDetail()
		}
		
		this.loadRegionData()
	},
	
	methods: {
		// 返回
		goBack() {
			uni.navigateBack()
		},
		
		// 加载地址详情
		async loadAddressDetail() {
			try {
				// 模拟API调用
				const result = await this.mockGetAddressDetail(this.addressId)
				this.form = { ...result.data }
			} catch (error) {
				uni.showToast({
					title: '加载失败',
					icon: 'none'
				})
			}
		},
		
		// 模拟获取地址详情
		mockGetAddressDetail(id) {
			return new Promise((resolve) => {
				setTimeout(() => {
					resolve({
						data: {
							id: id,
							name: '张三',
							phone: '13800138000',
							province: '广东省',
							city: '深圳市',
							district: '南山区',
							detail: '科技园南区深南大道10000号腾讯大厦',
							isDefault: true
						}
					})
				}, 300)
			})
		},
		
		// 加载地区数据
		loadRegionData() {
			// 模拟地区数据
			this.provinces = [
				{ name: '北京市', code: '110000' },
				{ name: '上海市', code: '310000' },
				{ name: '广东省', code: '440000' },
				{ name: '浙江省', code: '330000' },
				{ name: '江苏省', code: '320000' }
			]
			
			this.updateCities()
		},
		
		// 更新城市列表
		updateCities() {
			const provinceIndex = this.pickerValue[0]
			const province = this.provinces[provinceIndex]
			
			if (!province) {
				this.cities = []
				this.districts = []
				return
			}
			
			// 模拟城市数据
			switch (province.code) {
				case '110000': // 北京
					this.cities = [
						{ name: '北京市', code: '110100' }
					]
					break
				case '310000': // 上海
					this.cities = [
						{ name: '上海市', code: '310100' }
					]
					break
				case '440000': // 广东
					this.cities = [
						{ name: '广州市', code: '440100' },
						{ name: '深圳市', code: '440300' },
						{ name: '珠海市', code: '440400' }
					]
					break
				default:
					this.cities = [
						{ name: '市区', code: '000100' }
					]
			}
			
			this.updateDistricts()
		},
		
		// 更新区县列表
		updateDistricts() {
			const cityIndex = this.pickerValue[1]
			const city = this.cities[cityIndex]
			
			if (!city) {
				this.districts = []
				return
			}
			
			// 模拟区县数据
			switch (city.code) {
				case '440300': // 深圳
					this.districts = [
						{ name: '福田区', code: '440304' },
						{ name: '罗湖区', code: '440303' },
						{ name: '南山区', code: '440305' },
						{ name: '宝安区', code: '440306' }
					]
					break
				case '440100': // 广州
					this.districts = [
						{ name: '天河区', code: '440106' },
						{ name: '越秀区', code: '440104' },
						{ name: '海珠区', code: '440105' }
					]
					break
				default:
					this.districts = [
						{ name: '市辖区', code: '000101' }
					]
			}
		},
		
		// 显示地区选择器
		showRegionPicker() {
			this.showPicker = true
		},
		
		// 隐藏地区选择器
		hidePicker() {
			this.showPicker = false
		},
		
		// 选择器值改变
		onPickerChange(e) {
			const value = e.detail.value
			const oldValue = [...this.pickerValue]
			
			this.pickerValue = value
			
			// 如果省份改变，重置城市和区县
			if (value[0] !== oldValue[0]) {
				this.pickerValue[1] = 0
				this.pickerValue[2] = 0
				this.updateCities()
			}
			// 如果城市改变，重置区县
			else if (value[1] !== oldValue[1]) {
				this.pickerValue[2] = 0
				this.updateDistricts()
			}
		},
		
		// 确认选择地区
		confirmRegion() {
			const [provinceIndex, cityIndex, districtIndex] = this.pickerValue
			
			this.form.province = this.provinces[provinceIndex]?.name || ''
			this.form.city = this.cities[cityIndex]?.name || ''
			this.form.district = this.districts[districtIndex]?.name || ''
			
			this.hidePicker()
		},
		
		// 切换默认地址
		toggleDefault() {
			this.form.isDefault = !this.form.isDefault
		},
		
		// 默认地址开关改变
		onDefaultChange(e) {
			this.form.isDefault = e.detail.value
		},
		
		// 获取当前位置
		getCurrentLocation() {
			uni.showLoading({
				title: '定位中...'
			})
			
			uni.getLocation({
				type: 'gcj02',
				success: (res) => {
					this.reverseGeocode(res.latitude, res.longitude)
				},
				fail: (err) => {
					uni.hideLoading()
					uni.showToast({
						title: '定位失败，请检查定位权限',
						icon: 'none'
					})
				}
			})
		},
		
		// 逆地理编码
		reverseGeocode(latitude, longitude) {
			// 模拟逆地理编码
			setTimeout(() => {
				uni.hideLoading()
				
				// 模拟返回的地址信息
				this.form.province = '广东省'
				this.form.city = '深圳市'
				this.form.district = '南山区'
				this.form.detail = '科技园南区深南大道'
				
				uni.showToast({
					title: '定位成功',
					icon: 'success'
				})
			}, 1000)
		},
		
		// 保存地址
		async saveAddress() {
			if (!this.canSave) {
				return
			}
			
			// 验证手机号
			if (!/^1[3-9]\d{9}$/.test(this.form.phone)) {
				uni.showToast({
					title: '请输入正确的手机号',
					icon: 'none'
				})
				return
			}
			
			this.loading = true
			
			try {
				// 模拟保存API
				await new Promise(resolve => setTimeout(resolve, 1000))
				
				uni.showToast({
					title: this.isEdit ? '修改成功' : '添加成功',
					icon: 'success'
				})
				
				// 返回上一页
				setTimeout(() => {
					uni.navigateBack()
				}, 1500)
			} catch (error) {
				uni.showToast({
					title: '保存失败',
					icon: 'none'
				})
			} finally {
				this.loading = false
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.address-edit-container {
	min-height: 100vh;
	background: #f5f5f5;
	padding-top: var(--status-bar-height);
	padding-bottom: env(safe-area-inset-bottom);
}

.nav-bar {
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 44px;
	padding: 0 15px;
	background: #fff;
	border-bottom: 1px solid #eee;
	
	.nav-left,
	.nav-right {
		width: 44px;
		height: 44px;
		display: flex;
		align-items: center;
		justify-content: center;
		
		.iconfont {
			font-size: 20px;
			color: #333;
		}
	}
	
	.nav-title {
		font-size: 18px;
		font-weight: 500;
		color: #333;
	}
}

.form-container {
	height: calc(100vh - var(--status-bar-height) - 44px - 80px);
	padding: 10px;
}

.form-section {
	background: #fff;
	border-radius: 8px;
	margin-bottom: 10px;
	overflow: hidden;
}

.form-item {
	display: flex;
	align-items: flex-start;
	padding: 15px 20px;
	border-bottom: 1px solid #f0f0f0;
	
	&:last-child {
		border-bottom: none;
	}
	
	&.switch-item {
		align-items: center;
		justify-content: space-between;
	}
	
	.item-label {
		width: 80px;
		font-size: 16px;
		color: #333;
		flex-shrink: 0;
		line-height: 1.5;
	}
	
	.item-input {
		flex: 1;
		font-size: 16px;
		color: #333;
		padding: 0;
		margin: 0;
		background: transparent;
		border: none;
		outline: none;
		
		&::placeholder {
			color: #999;
		}
	}
	
	.item-textarea {
		flex: 1;
		font-size: 16px;
		color: #333;
		padding: 0;
		margin: 0;
		background: transparent;
		border: none;
		outline: none;
		min-height: 60px;
		resize: none;
		
		&::placeholder {
			color: #999;
		}
	}
	
	.item-content {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: space-between;
		
		.region-text {
			font-size: 16px;
			color: #333;
		}
		
		.placeholder-text {
			font-size: 16px;
			color: #999;
		}
		
		.iconfont {
			font-size: 14px;
			color: #999;
		}
	}
}

.location-section {
	padding: 20px;
	
	.location-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 8px;
		height: 44px;
		background: #f8f8f8;
		border-radius: 22px;
		border: 1px dashed #ddd;
		
		.iconfont {
			font-size: 16px;
			color: #007aff;
		}
		
		.location-text {
			font-size: 14px;
			color: #007aff;
		}
	}
}

.save-btn-container {
	position: fixed;
	bottom: 20px;
	left: 20px;
	right: 20px;
	margin-bottom: env(safe-area-inset-bottom);
	
	.save-btn {
		height: 50px;
		background: #007aff;
		border-radius: 25px;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 16px;
		color: #fff;
		font-weight: 500;
		
		&.disabled {
			background: #ccc;
			color: #999;
		}
	}
}

.region-picker {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 300px;
	background: #fff;
	z-index: 1000;
	
	.picker-item {
		height: 40px;
		line-height: 40px;
		text-align: center;
		font-size: 16px;
		color: #333;
	}
}

.picker-mask {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	z-index: 999;
	display: flex;
	flex-direction: column;
	justify-content: flex-end;
	
	.picker-header {
		height: 44px;
		background: #fff;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 15px;
		border-bottom: 1px solid #eee;
		
		.picker-cancel,
		.picker-confirm {
			font-size: 16px;
			color: #007aff;
		}
		
		.picker-title {
			font-size: 16px;
			color: #333;
			font-weight: 500;
		}
	}
}
</style>